package suanfa;

/**
 * @author zt
 * @date 2020-09-08 23:45
 */

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpServer {

    private ServerSocket server;
    private Socket socket;
    private int port;
    private InputStream inputStream;
    private static final int MAX_BUFFER_SIZE = 1024;

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public TcpServer(int port) {
        this.port = port;
    }

    public void runServerSingle() throws IOException {
        //创建服务器Socket对象
        this.server = new ServerSocket(this.port);
        //监听客户端连接,返回一个对应的Socket对象
        this.socket = server.accept();
        //获取输入流
        this.inputStream = this.socket.getInputStream();

        StringBuilder stringBuilder = new StringBuilder();
        byte[] readBytes = new byte[MAX_BUFFER_SIZE];

        //一次读取一个字节数组
        int msgLen = inputStream.read(readBytes);

        //字节数组的前2个byte表示所有内容的长度
        String firstField = new String(readBytes, 0, 2, "UTF-8");
        int length = Integer.parseInt(firstField);

        //字节数组的第3个byte表示类型
        String type = new String(readBytes, 2, 1, "UTF-8");

        //字节数组的第4个到第11个byte表示时间
        String time = new String(readBytes, 3, 8, "UTF-8");

        //data body的长度
        int bodyLen = length - 11;

        //从字节数组的第12个byte开始表示data body
        String body = new String(readBytes, 11, msgLen-11, "UTF-8");
        stringBuilder.append(body);

        //判断首次接收是否全部完成,如果没接收完,则在while循环里继续接收
        if (bodyLen > msgLen - 11) {
            while ((msgLen = inputStream.read(readBytes)) != -1) {
                stringBuilder.append(new String(readBytes, 0, msgLen, "UTF-8"));
            }
        }
        System.out.println("tpye:" + type);
        System.out.println("time:" + time);
        System.out.println("data body:" + stringBuilder.toString());

        //释放资源
        inputStream.close();
        socket.close();
        server.close();
    }

    public static void main(String[] args) {
        TcpServer tcpServer = new TcpServer(8888);
        try {
            tcpServer.runServerSingle();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
